#!/usr/bin/python
#-*- coding: utf-8 -*-

import sys
reload(sys)

from  salt_api import SaltAPI

import threading
import ConfigParser
import  db, conf
import MySQLdb

cur = db.db_object()

asset_info = []

def get_server_asset_info(tgt, url, user, passwd, device):
    '''
    Salt API得到资产信息，进行格式化输出
    '''

    cf = ConfigParser.ConfigParser()
    cf.read('config.ini')

    global asset_info
    info = []
    sapi = SaltAPI(url=url, username=user, password=passwd)
    ret = sapi.remote_noarg_execution(tgt, 'discovery.Discovery')
    host_id = ret['id']
    info.append(host_id)
    host_ip = ret['ip4_interfaces'][device]
    info.append(host_ip)
    ret["hwaddr_interfaces"].pop("lo")
    hwaddr_interfaces = str(ret["hwaddr_interfaces"]).replace(",", " |")
    info.append(hwaddr_interfaces)
    cpu_model = ret['cpu_model']
    info.append(cpu_model)
    num_cpus = int(ret['num_cpus'])
    info.append(num_cpus)
    mem_total = ret['mem_total']
    info.append(mem_total)
    disk_size = ret['disk_size']
    info.append(disk_size)
    kernelrelease = ret['kernelrelease']
    info.append(kernelrelease)
    sys_ver = ret['osfullname'] + ret['osrelease'] + '-' + ret['osarch']
    info.append(sys_ver)
    vt = ret['virtual']
    info.append(vt)
    asset_info.append(info)
    return asset_info


##自动采集主机入库
    cur.execute('select host_id from salt_stack')  ###获取资产列表中的主机名
    L = []
    for host in cur.fetchall():
        L.append(host[0])
    hostnames = ''.join(L)

    if host_id in hostnames:  ##判断主机是否已经入库，如果存在输出提示，不存在则入库
        T = [(str(host_id), str(host_ip), str(hwaddr_interfaces), str(cpu_model), int(num_cpus), str(mem_total),
              str(disk_size), str(sys_ver), str(kernelrelease))]
        sql = 'update salt_stack set host_ip=%s, cpu_model=%s, num_cpus=%s, hwaddr_interfaces=%s, mem_total=%s, disk_size=%s, sys_ver=%s, kernelrelease=%s, where host_id=%s'
        cur.executemany(sql, T)
        print "%s 已经在资产列表！" % host_id
    else:
        T = [(str(host_id), str(host_ip), str(hwaddr_interfaces), str(cpu_model), int(num_cpus), str(mem_total),
              str(disk_size), str(sys_ver), str(kernelrelease))]
        sql = 'insert into salt_stack (host_id, host_ip, hwaddr_interfaces, cpu_model, num_cpus, mem_total, disk_size, sys_ver, kernelrelease) values (%s, %s ,%s, %s, %s ,%s, %s, %s, %s)'
        cur.executemany(sql, T)


if __name__ == '__main__':
    print get_server_asset_info('Home-Lnmp','https://192.168.0.12:8000','saltapi','saltapi','eth0')









